<template>
<div>
  <q-dialog v-model="show" persistent class="add-quality-item">
    <q-card v-drag class="dialog-content" style="min-width: 1000px; max-height: 800px">
      <q-card-section class="dialog-title bg-primary" >
        <div class="text-center text-white dialog-title">
          <span class="font-size-16">不良录入 [ {{details.id}} ] </span>
<!--          <q-btn-->
<!--            style="font-size: 18px;color: white"-->
<!--            flat round dense-->
<!--            class="iconfont icontubiao-67 white close-btn dialog"-->
<!--            @click="$emit('close')"-->
<!--          />-->
        </div>
      </q-card-section>
      <q-card-section class="row form-inline" style="padding: 12px 20px 8px">
        <div class="col-3"><text-label :label="'产品名称'" :value="details.productName+'('+details.productNumber+')'"/></div>
        <div class="col-3"><text-label :label="'工单编号'" :value="details.workOrderId"/></div>
        <div class="col-3"><text-label :label="'订单编号'" :value="details.orderNumber"/></div>
        <div class="col-3"><text-label :label="'批次编号'" :value="details.orderBatch"/></div>
        <div class="col-3"><text-label :label="'加工工序'" :value="process"/></div>
        <div class="col-3"><text-label :label="'加工设备'" :value="details.deviceName+'('+details.deviceNumber+')'"/></div>
        <div class="col-3"><text-label :label="'检验数量'" :value="details.qualityControlCount"/></div>
        <div class="col-3"><text-label :label="'质检人员'" :value="details.personalName ? details.personalName:userInfo.user_nickname"/></div>
        <div class="col-3"><text-label :label="'合格数量'" :value="details.qualityControlCount - details.defectiveCount"/></div>
      </q-card-section>
      <q-toolbar class="tab">
              <q-tabs v-model="tab"
                      shrink stretch dense
                      inline-label
                      align="left"
                      active-color="primary"
                      indicator-color="primary"
              >
                <q-tab name="bad"  label="不良品录入" />
                <q-tab name="compromise"  label="让步品录入" />
              </q-tabs>
        </q-toolbar>
      <q-separator class="line"/>
      <q-form greedy @submit="submitQuality" ref="submitQuality" class="margin-t-20">
        <!-- 不良品录入 -->
        <q-card style="margin: 0 20px 20px;box-shadow:none" v-show="tab === 'bad'">
          <q-card-section class="dialog-title bg-primary" >
            <div class="text-center text-white dialog-title" style="padding-left: 0;text-align: left;">
              <span class="font-size-16">不良录入表</span>
              <q-btn
                style="font-size: 18px;color: white"
                flat round dense
                class="iconfont icontubiao-50 white close-btn dialog"
                @click="addDefectiveCauses"
              />
            </div>
          </q-card-section>
          <q-card-section class="bordered scroll-box" style="padding:10px; max-height: 370px">
            <div v-for="(item, index) in defectiveData" :key="index" class="q-mt-sm q-mb-sm">
              <div class="flex">
                <div style="width:80px; text-align:center;line-height:100px">{{item.indexId + 1}}</div>
                <div  style="flex:1">
                <div class="row">
                <q-select
                    class="select col"
                    outlined dense emit-value map-options options-dense
                    :options="shiftsList"
                    v-model="item.shiftsId"
                    style="width: 270px"
                    @input="onInput"
                    :rules="[val => repeat('defective', item.shiftsId, item.defective, item.indexId)  || '同班次下已选相同不良原因']"
                  >
                    <template v-slot:no-option>
                      <div class="no-option"/>
                    </template>
                    <template v-slot:before>
                      <span class="font-size-16 text-black fuck-width">加工班次:</span>
                    </template>
                  </q-select>
                                    <q-select
                    class="select col q-ml-sm"
                    outlined dense emit-value map-options options-dense
                    :options="partscauseList"
                    v-model="item.gid"
                    style="width: 270px"
                    @input="getPartscauseItem(item.gid, item.indexId)"
                    :rules="[val => val !== null || '请选择原因类型']"
                  >
                    <template v-slot:no-option>
                      <div class="no-option"/>
                    </template>
                      <template v-slot:before>
                      <span class="font-size-16 text-black fuck-width">不良类型:</span>
                    </template>
                  </q-select>

                                    <q-select
                    class="select col q-ml-sm"
                    outlined dense emit-value map-options options-dense
                    :options="item.partscauseItemList"
                    v-model="item.defective"
                    style="width: 270px"
                    @input="onInput"
                    :rules="[
                       val => repeat('defective',item.shiftsId, item.defective, item.indexId) || '同班次下已选相同不良原因',
                       val => isNull(val) || '请选择不良原因'
                     ]"
                  >
                    <template v-slot:no-option>
                      <div class="no-option"/>
                    </template>
                    <template v-slot:before>
                      <span class="font-size-16 text-black fuck-width">不良原因:</span>
                    </template>
                  </q-select>
                                  </div>
                <div class="flex" style="margin-top:2px">
                  <q-input
                    v-model.number="item.count" outlined dense
                    style="width:258px"
                    :rules="[val =>  /^[1-9]\d*$/.test(val) && val > 0 || '请输入有效数字',
                              val => repeatCount() || '不良品与让步品已超出'
                    ]"
                    :ref="'count_' + item.indexId"
                    @input="inputChange"
                  >
                   <template v-slot:before>
                      <span class="font-size-16 text-black fuck-width" style="text-align: right">数量:</span>
                    </template>
                  </q-input>
                  <q-input
                    v-model.trim="item.remark"
                    type="textarea" counter autogrow maxlength="50"
                    style="min-width:490px; margin-left:40px"
                    outlined
                    class="textarea">
                   <template v-slot:before>
                      <span class="font-size-16 text-black">说明:</span>
                    </template>
                   <template v-slot:append>
                      <q-icon name="iconfont icontubiao2-93" color="primary" class="cursor-pointer" @click="onShowSymbol(item, index)"/>
                  </template>
                    </q-input>
                    </div>
                  </div>
                  <div class="text-center" style="width:60px; line-height:100px">
                  <q-btn
                    flat round dense
                    icon="iconfont icontubiao-16"
                    color="primary"
                    @click="delQualityItem('defective', item.indexId)"
                  >
                    <q-tooltip>删除</q-tooltip>
                  </q-btn>
                  </div>
                  </div>
                  <q-separator class="line"/>
            </div>
          </q-card-section>
        </q-card>
        <!-- 不良品录入End -->
        <!-- 让步品录入 -->
        <q-card style="margin: 0 20px 20px; box-shadow:none" v-show="tab === 'compromise'">
          <q-card-section class="dialog-title bg-primary" >
            <div class="text-center text-white dialog-title" style="padding-left: 0;text-align: left;">
              <span class="font-size-16">让步录入表</span>
              <q-btn
                style="font-size: 18px;color: white"
                flat round dense
                class="iconfont icontubiao-50 white close-btn dialog"
                @click="addCompromiseCauses"
              />
            </div>
          </q-card-section>
          <q-card-section class="bordered scroll-box" style="padding:10px; max-height: 370px">
            <div v-for="(item, index) in compromiseData" :key="index" class="q-mt-sm q-mb-sm">
              <div class="flex">
                <div style="width:80px; text-align:center;line-height:100px">{{item.indexId + 1}}</div>
                <div  style="flex:1">
                <div class="row">
                 <q-select
                    class="select col"
                    outlined dense emit-value map-options options-dense
                    :options="shiftsList"
                    v-model="item.shiftsId"
                    @input="onInput"
                    :rules="[val => repeat('compromise', item.shiftsId, item.concession, item.indexId) || '同班次下已选相同让步原因']"
                  >
                    <template v-slot:no-option>
                      <div class="no-option"/>
                    </template>
                    <template v-slot:before>
                      <span class="font-size-16 text-black">加工班次:</span>
                    </template>
                  </q-select>
                    <q-select
                    class="select col  q-ml-sm"
                    outlined dense emit-value map-options options-dense
                    :options="concessionList"
                    v-model="item.concession"
                    @input="onInput"
                    :rules="[val => repeat('compromise', item.shiftsId, item.concession, item.indexId) || '同班次下已选相同让步原因',
                     val => isNull(val) || '请选择让步原因']"
                  >
                    <template v-slot:no-option>
                      <div class="no-option"/>
                    </template>
                      <template v-slot:before>
                      <span class="font-size-16 text-black">让步原因:</span>
                    </template>
                  </q-select>
                  <q-input
                    v-model.number="item.count" outlined dense
                    class="col q-ml-sm"
                    :rules="[val =>  /^[1-9]\d*$/.test(val) && val > 0 || '请输入有效数字',
                              val => repeatCount() || '不良品与让步品已超出'
                    ]"
                    :ref="'count_' + item.indexId"
                    @input="inputChange"
                  >
                   <template v-slot:before>
                      <span class="font-size-16 text-black">数量:</span>
                    </template>
                  </q-input>
                 </div>
                <div class="row" style="margin-top:5px">
                <q-input
                    v-model.trim="item.remark"
                    type="textarea" counter autogrow maxlength="50"
                    style="min-width:180px"
                    outlined
                    class="textarea col">
                   <template v-slot:before>
                      <span class="font-size-16 text-black">说明:</span>
                    </template>
                    <template v-slot:append>
                     <q-icon name="iconfont icontubiao2-93" color="primary" class="cursor-pointer" @click="onShowSymbol(item, index)" />
                  </template>
                    </q-input>
                    </div>
                  </div>
                  <div class="text-center" style="width:60px; line-height:100px">
                  <q-btn
                    flat round dense
                    icon="iconfont icontubiao-16"
                    color="primary"
                    @click="delQualityItem('compromise', item.indexId)"
                  >
                    <q-tooltip>删除</q-tooltip>
                  </q-btn>
                  </div>
                  </div>
                  <q-separator class="line"/>
            </div>
          </q-card-section>
        </q-card>
        <!-- 让步品录入End -->
        <!-- 底部按钮 -->
        <q-separator />
        <div class="dialog-footer text-center margin-t-10">
          <q-btn outline label="取消" color="primary" @click="$emit('close')" class="q-mr-md"/>
          <q-btn unelevated label="确认" color="primary" type="submit" :disable="compromiseData.length + defectiveData.length <= 0"/>
        </div>
      </q-form>
    </q-card>
  </q-dialog>
    <add-symbol-dialog :show="isShowSymbol" @close="isShowSymbol = false" @onSetItem="onSetItem"></add-symbol-dialog>
    </div>
</template>

<script>
import textLabel from './text-label'
import { mapGetters } from 'vuex'
import { getShiftsList } from '../../../boot/job/man-machine-bind'
import { getCauseItem } from '../../../boot/system/reason'
import addSymbolDialog from './add-symbol-dialog'
export default {
  name: 'add-quality-item',
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  props: {
    show: {
      type: Boolean,
      default: false,
      required: true
    },
    selItem: {
      required: true
    },
    concessionList: {
      default: [],
      required: true
    },
    concessionDetail: {
      default: {},
      required: true
    },
    partscauseList: {
      default: [],
      required: true
    },
    partscauseItemList: {
      default: [],
      required: false
    },
    partscauseItemDetail: {
      default: [],
      required: true
    }
  },
  components: {
    textLabel,
    addSymbolDialog
  },
  data () {
    return {
      symbolData: null,
      isShowSymbol: false, // 符号弹窗
      details: {}, // 详情信息
      process: '', // 工序
      // 表格不分页
      pagination: {
        rowsPerPage: 0
      },
      // 不良头部信息
      defectiveColumns: [
        { name: 'indexId', label: '序号', field: 'indexId', align: 'left' },
        { name: 'shifts', label: '加工班次', field: 'shifts', align: 'left' },
        { name: 'gid', label: '不良类型', field: 'gid', align: 'left' },
        { name: 'defective', label: '不良原因', field: 'defective', align: 'left' },
        { name: 'count', label: '数量', field: 'count', align: 'left' },
        // 13期 增加字段说明信息
        { name: 'remark', label: '说明', field: 'remark', align: 'left' },
        { name: 'operate', label: '操作', field: 'operate', align: 'center' }
      ],
      // 不良录入列表
      defectiveData: [],
      // 让步头部信息
      compromiseColumns: [
        { name: 'indexId', label: '序号', field: 'indexId', align: 'left' },
        { name: 'shifts', label: '加工班次', field: 'shiftsId', align: 'left' },
        { name: 'concession', label: '让步原因', field: 'concession', align: 'left' },
        { name: 'count', label: '数量', field: 'count', align: 'left' },
        // 13期 增加字段说明信息
        { name: 'remark', label: '说明', field: 'remark', align: 'left' },
        { name: 'operate', label: '操作', field: 'operate', align: 'center' }
      ],
      // 让步录入列表
      compromiseData: [],
      shiftsList: [], // 轮班下拉数据
      shiftsDetail: {}, // 轮班详细
      waitInput: 0, // 待录入数
      tab: 'bad'
    }
  },
  methods: {
    // 提交
    submitQuality () {
      let params = []

      // 不良录入
      if (this.defectiveData.length > 0) {
        this.defectiveData.forEach(item => {
          let itemParams = {
            count: Number(item.count),
            causeId: item.defective,
            gid: item.gid,
            // 13期
            remark: item.remark,
            label: item.partscauseItemDetail[item.defective],
            orderId: this.details.id,
            shiftsId: item.shiftsId,
            isQualityControl: true,
            deviceId: this.details.deviceId
          }
          params.push(itemParams)
        })
      }
      // 让步录入
      if (this.compromiseData.length > 0) {
        this.compromiseData.forEach(item => {
          let itemParams = {
            count: Number(item.count),
            causeId: item.concession,
            label: this.concessionDetail[item.concession],
            orderId: this.details.id,
            // 13期
            remark: item.remark,
            shiftsId: item.shiftsId,
            isQualityControl: true,
            deviceId: this.details.deviceId
          }
          params.push(itemParams)
        })
      }
      this.$emit('batchCreateQuality', params)
    },
    // 判断是否为空
    isNull (val) {
      if (val) {
        return true
      } else {
        return false
      }
    },
    // 新增不良原因行
    addDefectiveCauses () {
      let item = {
        shiftsId: null,
        remark: '',
        gid: null,
        partscauseItemList: this.partscauseItemList,
        partscauseItemDetail: this.partscauseItemDetail,
        count: 1
      }
      if (this.shiftsList.length > 0) {
        item['shiftsId'] = this.shiftsList[0].value
      }
      if (this.partscauseList.length > 0) {
        item['gid'] = this.partscauseList[0].value
      }
      if (this.partscauseItemList.length > 0) {
        item.defective = this.partscauseItemList[0].value
      } else {
        item.defective = null
      }
      if (this.defectiveData.length > 0) {
        item.indexId = this.defectiveData.length
      } else {
        item.indexId = 0
      }
      this.defectiveData.push(item)
      const dom = this.$refs.submitQuality
      setTimeout(() => {
        dom.validate()
      }, 0)
    },
    // 新增让步原因行
    addCompromiseCauses () {
      const item = {
        shiftsId: null,
        concession: null,
        remark: '',
        count: 1
      }
      if (this.shiftsList.length > 0) {
        item['shiftsId'] = this.shiftsList[0].value
      }
      if (this.concessionList.length > 0) {
        item.concession = this.concessionList[0].value
      }
      if (this.compromiseData.length > 0) {
        item.indexId = this.compromiseData.length
      } else {
        item.indexId = 0
      }
      this.compromiseData.push(item)
      const dom = this.$refs.submitQuality
      setTimeout(() => {
        dom.validate()
      }, 0)
    },
    repeat (type, shiftsId, cause, index) {
      let flag = true
      if (type === 'compromise') {
        if (this.compromiseData.length > 0) {
          this.compromiseData.forEach(i => {
            // console.log(i)
            if (i.indexId !== index && i.shiftsId === shiftsId && i.concession === cause) {
              flag = false
            }
          })
        }
      } else if (type === 'defective') {
        if (this.defectiveData.length > 0) {
          this.defectiveData.forEach(i => {
            if (i.indexId !== index && i.shiftsId === shiftsId && i.defective === cause) {
              flag = false
            }
          })
        }
      }
      return flag
    },
    // 校验
    repeatCount () {
      let flag = true
      let count = 0
      if (this.compromiseData.length > 0) {
        this.compromiseData.forEach(i => {
          count += Number(i.count)
          if (count > this.waitInput) {
            flag = false
            return false
          }
        })
      }
      if (this.defectiveData.length > 0) {
        this.defectiveData.forEach(i => {
          count += Number(i.count)
          if (count > this.waitInput) {
            flag = false
            return false
          }
        })
      }
      return flag
    },
    // 删除行
    delQualityItem (type, index) {
      if (type === 'compromise') {
        this.compromiseData.splice(index, 1)
        this.compromiseData.forEach((i, index) => {
          console.log(index, 'index')
          i.indexId = index
        })
      } else if (type === 'defective') {
        this.defectiveData.splice(index, 1)
        this.defectiveData.forEach((i, index) => {
          console.log(index, 'index')
          i.indexId = index
        })
      }
    },
    // 获取轮班列表
    getShiftsList (id) {
      const params = {
        id: id
      }
      getShiftsList(params).then(res => {
        this.shiftsList = []
        if (res.data.length > 0) {
          res.data.forEach(o => {
            // 轮班map（为提交轮班名）
            this.shiftsDetail[o.id] = {
              shiftsModeId: o.shiftsModeId,
              name: o.name
            }
            this.shiftsList.push({
              value: o.id,
              label: o.name
            })
          })
        }
      }).catch(() => {
        console.log('获取数据失败')
      })
    },
    // 触发校验
    onInput () {
      this.$refs.submitQuality.validate()
    },
    inputChange () {
      if (this.compromiseData.length > 0) {
        this.compromiseData.forEach(i => {
          this.$refs[`count_${i.indexId}`].validate()
        })
      }
      if (this.defectiveData.length > 0) {
        this.defectiveData.forEach(i => {
          this.$refs[`count_${i.indexId}`].validate()
        })
      }
    },
    // 根据零件不良原因类型代码查询零件不良原因
    getPartscauseItem (typeId, index) {
      const params = {
        id: typeId,
        showDisable: false
      }
      this.defectiveData[index].partscauseItemList = []
      this.defectiveData[index].partscauseItemDetail = {}
      this.$set(this.defectiveData[index], 'defective', '')
      getCauseItem(params).then(res => {
        if (res.data.length > 0) {
          let partscauseList = []
          res.data.forEach(o => {
            // 让步原因map（为取让步名）
            this.defectiveData[index].partscauseItemDetail[o.id] = o.label
            partscauseList.push({
              value: o.id,
              label: o.label
            })
          })
          this.$nextTick(() => {
            this.$set(this.defectiveData[index], 'partscauseItemList', partscauseList)
            this.$set(this.defectiveData[index], 'defective', res.data[0].id)
          })
        } else {
          this.defectiveData[index].defective = null
        }
        this.$refs.submitQuality.validate()
      })
    },
    onShowSymbol (item, index) {
      this.symbolData = item
      this.isShowSymbol = true
    },
    onSetItem (val) {
      this.symbolData.remark = `${this.symbolData.remark}${val}`
      this.isShowSymbol = false
    }
  },
  watch: {
    selItem (val) {
      this.details = val
      this.waitInput = val.qualityControlCount - val.defectiveCount - val.compromiseCount
      if (!val.qualityControlPersonalName) {
        this.details.personalName = null
      }
      this.process = `${val.sort}-${val.processName}`
      this.getShiftsList(val.workshopId)
    },
    show () {
      this.defectiveData = []
      this.compromiseData = []
    }
  }
}
</script>

<style scoped lang="stylus">
  .bordered,.bordered:last-child {
    border-bottom  1px
    border-top 0
    border 1px solid #D3D3D3
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
  }
  .p-t-10{
    padding-top 10px
  }
  .fuck-width{
    width 68px
  }
</style>
